package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //1、获取操作人id----->当前登录人的ID----->从token中获取----->token在请求头中----->request.getHeader("token")
        //1.1   获取token中的jwt令牌
        String jwt = request.getHeader("token");
        //1.2   解析令牌
        Claims claims = JwtUtils.parseJWT(jwt);
        //1.3   获取用户ID
        Integer operateEmpId = (Integer) claims.get("id");
        String operateEmpName = (String) claims.get("name");

        //获取当前操作时间
        LocalDateTime operateTime = LocalDateTime.now();


        //获取操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //获取操作方法名
        String methodName = joinPoint.getSignature().getName();

        //获取操作参数名
        String methodParams = Arrays.toString(joinPoint.getArgs());

        //获取原始目标方法执行之前的时间
        long begin = System.currentTimeMillis();
        //调用原始方法
        Object result = joinPoint.proceed();
        //获取原始目标方法执行之后的时间
        long end = System.currentTimeMillis();

        //获取操作返回值
        String resultValue = result.toString();
        OperateLog operateLog  =new OperateLog(null,operateEmpId,operateTime,className,methodName,methodParams,resultValue,end-begin,operateEmpName);

        //调用mapper层插入日志
        operateLogMapper.insert(operateLog);

        return result ;
    }
}
